package com.hydra.framework.thread;

import android.os.SystemClock;
import androidx.annotation.NonNull;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ScheduledThreadPoolAsyncAdapter implements ThreadAsyncAdapter {

    private ScheduledThreadPoolExecutor mPoolExecutor;

    public ScheduledThreadPoolAsyncAdapter(int corePoolSize) {
        mPoolExecutor = new ScheduledThreadPoolExecutor(corePoolSize);
    }

    @Override
    public boolean post(Runnable r) {
        Future<?> future = mPoolExecutor.schedule(r, 0, TimeUnit.NANOSECONDS);
        return future != null;
    }

    @Override
    public boolean postDelayed(@NonNull Runnable r, long delayMillis) {
        Future<?> future = mPoolExecutor.schedule(r, delayMillis, TimeUnit.MILLISECONDS);
        return future != null;
    }

    @Override
    public boolean postAtTime(Runnable r, long uptimeMillis) {
        return postDelayed(r, Math.max(uptimeMillis - SystemClock.uptimeMillis(), 0));
    }

    @Override
    public void removeCallbacks(Runnable r, Object token) {
        mPoolExecutor.remove(r);
    }

    @Override
    public void quit() {
        mPoolExecutor.shutdown();
    }

    @Override
    public boolean isCurrentThread() {
        return false;
    }
}
